package com.tanhua.server.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import com.tanhua.common.pojo.User;
import com.tanhua.common.pojo.UserInfo;
import com.tanhua.common.utils.RelativeDateFormat;
import com.tanhua.common.utils.UserThreadLocal;
import com.tanhua.dubbo.server.api.VisitorsApi;
import com.tanhua.dubbo.server.pojo.Comment;
import com.tanhua.dubbo.server.api.QuanZiApi;
import com.tanhua.dubbo.server.pojo.Publish;
import com.tanhua.dubbo.server.pojo.Visitors;
import com.tanhua.dubbo.server.vo.PageInfo;
import com.tanhua.server.vo.CommentVo;
import com.tanhua.server.vo.PageResult;
import com.tanhua.server.vo.QuanZiVo;
import com.tanhua.server.vo.VisitorsVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;


import java.util.*;

@Service
public class QuanZiService {
    @Reference(version = "1.0.0",check = false)
    private QuanZiApi quanZiApi;
    @Autowired
    private UserInfoService userInfoService;
    @Reference(version = "1.0.0",check = false)
    private VisitorsApi visitorsApi;
    @Autowired
    private UserService userService;
    @Autowired
    private QuanziMQService quanziMQService;
    public PageResult querypublishlist(Integer page, Integer pagesize) {
        PageResult pageResult = new PageResult();
        pageResult.setPage(page);
        pageResult.setPagesize(pagesize);
        User user = UserThreadLocal.get();
        PageInfo<Publish> pageInfo = quanZiApi.queryPublishList(user.getId(), page, pagesize);
        List<Publish> records = pageInfo.getRecords();
        if(CollUtil.isEmpty(records)){
            return pageResult;
        }pageResult.setItems(fillQuanZiVo(records));
        return pageResult;
    }

    private List<QuanZiVo> fillQuanZiVo(List<Publish> records) {
        List<QuanZiVo> quanZiVoList = new ArrayList<>();
        records.forEach(publish ->{
            QuanZiVo quanZiVo = new QuanZiVo();
            quanZiVo.setId(publish.getId().toHexString());
            quanZiVo.setTextContent(publish.getText());
            quanZiVo.setImageContent(publish.getMedias().toArray(new String[]{}));
            quanZiVo.setUserId(publish.getUserId());
            quanZiVo.setCreateDate(RelativeDateFormat.format(new Date(publish.getCreated())));
            quanZiVoList.add(quanZiVo);
        } );
        List<Object> userIds = CollUtil.getFieldValues(records, "userId");
        List<UserInfo> userInfos = userInfoService.queryUserInfoByUserIdList(userIds);
        for (QuanZiVo quanZiVo : quanZiVoList) {
            for (UserInfo userInfo : userInfos) {
                if(quanZiVo.getUserId().longValue()==userInfo.getUserId().longValue()){
                    fillUserInfoToQuanZiVo(userInfo, quanZiVo);
                    break;
                }
            }
        }return quanZiVoList;
    }

    private void fillUserInfoToQuanZiVo(UserInfo userInfo, QuanZiVo quanZiVo) {
        BeanUtils.copyProperties(userInfo,quanZiVo,"id");
        quanZiVo.setGender(userInfo.getSex().name().toLowerCase());
        quanZiVo.setTags(StringUtils.split(userInfo.getTags(),","));
        quanZiVo.setAvatar(userInfo.getLogo());
        quanZiVo.setNickname(userInfo.getNickName());
        User user = UserThreadLocal.get();
        quanZiVo.setCommentCount(0); //TODO 评论数
        quanZiVo.setDistance("1.2公里"); //TODO 距离
        quanZiVo.setHasLiked(quanZiApi.queryUserIsLike(user.getId(),quanZiVo.getId())?1:0);
        quanZiVo.setLikeCount(Convert.toInt(quanZiApi.queryLikeCount(quanZiVo.getId())));
        quanZiVo.setHasLoved(quanZiApi.queryUserIsLove(user.getId(),quanZiVo.getId())?1:0); //TODO 是否喜欢（1是，0否）
        quanZiVo.setLoveCount(Convert.toInt(quanZiApi.queryLoveCount(quanZiVo.getId()))); //TODO 喜欢数

    }

    public String savepublish(String textContent, MultipartFile[] multipartFile, String location, String longitude, String latitude) {
        User user = UserThreadLocal.get();
        Publish publish = new Publish();
        publish.setUserId(user.getId());
        publish.setText(textContent);
        publish.setLocationName(location);
        publish.setLatitude(latitude);
        publish.setLongitude(longitude);
        publish.setSeeType(1);
        List<String> picurls = new ArrayList<>();
        for (MultipartFile file : multipartFile) {
            //PicUploadResult picUploadResult = this.picUploadService.upload(file);
            // 获取上传后的图片地址
            //picUrls.add(picUploadResult.getName());
            picurls.add("https://tanhua-dev.oss-cn-zhangjiakou.aliyuncs.com/photo/6/CL-8.jpg");
        }
         publish.setMedias(picurls);
        String publishId = quanZiApi.savePublish(publish);
        if(StrUtil.isNotEmpty(publishId)){
            this.quanziMQService.publishMsg(publishId);
        }

        return publishId;
    }

    public PageResult queryRecommendPublishList(Integer page, Integer pagesize) {
        PageResult pageResult = new PageResult();
        pageResult.setPage(page);
        pageResult.setPagesize(pagesize);
        User user = UserThreadLocal.get();
        PageInfo<Publish> pageInfo = quanZiApi.queryRecommendPublishList(user.getId(), page, pagesize);
        List<Publish> records = pageInfo.getRecords();
        if(CollUtil.isEmpty(records)){
            return pageResult;
        }pageResult.setItems(fillQuanZiVo(records));
        return pageResult;
    }

    public PageResult queryCommentlist(String publishId, Integer page, Integer pagesize) {
        PageResult pageResult = new PageResult();
        pageResult.setPage(page);
        pageResult.setPagesize(pagesize);
        User user = UserThreadLocal.get();
        PageInfo<Comment> pageInfo = quanZiApi.queryCommentList(publishId, page, pagesize);
        List<Comment> records = pageInfo.getRecords();
        if(CollUtil.isEmpty(records)){
            return pageResult;
        }
        List<Object> userIds = CollUtil.getFieldValues(records, "userId");
        List<UserInfo> userInfoList = userInfoService.queryUserInfoByUserIdList(userIds);
        List<CommentVo> result = new ArrayList<>();
        for (Comment record : records) {
            CommentVo commentVo = new CommentVo();
            commentVo.setContent(record.getContent());
            commentVo.setId(record.getId().toHexString());
            commentVo.setCreateDate(DateUtil.format(new Date(record.getCreated()),"HH:mm"));
            commentVo.setHasLiked(quanZiApi.queryUserIsLike(user.getId(),commentVo.getId())?1:0);
            commentVo.setLikeCount(Convert.toInt(quanZiApi.queryLikeCount(commentVo.getId())));
            for (UserInfo userInfo : userInfoList) {
                if (ObjectUtil.equals(record.getUserId(),userInfo.getUserId())){
                    commentVo.setAvatar(userInfo.getLogo());
                    commentVo.setNickname(userInfo.getNickName());
                    break;
                }
            }result.add(commentVo);
        } pageResult.setItems(result);
        return pageResult;
    }

    public Boolean saveComments(String publishId, String content) {
        User user = UserThreadLocal.get();
        Boolean result = quanZiApi.saveComment(user.getId(), publishId, content);
        if(result){
            this.quanziMQService.commentPublishMsg(publishId);
        }
        return result;
    }
    public Long likeComment(String publishId) {
        User user = UserThreadLocal.get();
        Boolean result = quanZiApi.likeComment(user.getId(), publishId);
        if(result){
            quanziMQService.likePublishMsg(publishId);
            Long likeCount = quanZiApi.queryLikeCount(publishId);
            return likeCount;
        }return null;
    }

    public Long dislikeComment(String publishId) {
        User user = UserThreadLocal.get();
        Boolean result = quanZiApi.disLikeComment(user.getId(), publishId);
        if(result){
            quanziMQService.likePublishMsg(publishId);
            Long likeCount = quanZiApi.queryLikeCount(publishId);
            return likeCount;
        }return null;
    }

    public Long loveComment(String publishId) {
        User user = UserThreadLocal.get();
        Boolean result = quanZiApi.loveComment(user.getId(), publishId);
        if(result){
            quanziMQService.lovePublishMsg(publishId);
            Long loveCount = quanZiApi.queryLoveCount(publishId);
            return loveCount;
        }return null;
    }

    public Long disloveComment(String publishId) {
        User user = UserThreadLocal.get();
        Boolean result = quanZiApi.disLoveComment(user.getId(), publishId);
        if(result){
            quanziMQService.disLovePublishMsg(publishId);
            Long loveCount = quanZiApi.queryLoveCount(publishId);
            return loveCount;
        }return null;
    }

    public QuanZiVo queryById(String publishId) {
        Publish publish = quanZiApi.queryPublishById(publishId);
        if (ObjectUtil.isEmpty(publish)){
            return null;
        } quanziMQService.queryPublishMsg(publishId);
        return fillQuanZiVo(Arrays.asList(publish)).get(0);
    }
    public PageResult queryCommentList(String publishId, Integer page, Integer pageSize) {

        PageResult pageResult = new PageResult();
        pageResult.setPage(page);
        pageResult.setPagesize(pageSize);

        User user = UserThreadLocal.get();

        //查询评论列表数据
        PageInfo<Comment> pageInfo = this.quanZiApi.queryCommentList(publishId, page, pageSize);
        List<Comment> records = pageInfo.getRecords();
        if(CollUtil.isEmpty(records)){
            return pageResult;
        }

        //查询用户信息
        List<Object> userIdList = CollUtil.getFieldValues(records, "userId");
        List<UserInfo> userInfoList = this.userInfoService.queryUserInfoByUserIdList(userIdList);

        List<CommentVo> result = new ArrayList<>();
        for (Comment record : records) {
            CommentVo commentVo = new CommentVo();
            commentVo.setContent(record.getContent());
            commentVo.setId(record.getId().toHexString());
            commentVo.setCreateDate(DateUtil.format(new Date(record.getCreated()), "HH:mm"));
            //是否点赞
            commentVo.setHasLiked(this.quanZiApi.queryUserIsLike(user.getId(), commentVo.getId()) ? 1 : 0);
            //点赞数
            commentVo.setLikeCount(Convert.toInt(this.quanZiApi.queryLikeCount(commentVo.getId())));


            for (UserInfo userInfo : userInfoList) {
                if(ObjectUtil.equals(record.getUserId(), userInfo.getUserId())){

                    commentVo.setAvatar(userInfo.getLogo());
                    commentVo.setNickname(userInfo.getNickName());

                    break;
                }
            }

            result.add(commentVo);
        }

        pageResult.setItems(result);

        return pageResult;
    }
    public PageResult queryAlbumList(Long userId, Integer page, Integer pageSize) {
        PageResult pageResult = new PageResult();
        pageResult.setPage(page);
        pageResult.setPagesize(pageSize);

        //查询数据
        PageInfo<Publish> pageInfo = this.quanZiApi.queryAlbumList(userId, page, pageSize);
        if(CollUtil.isEmpty(pageInfo.getRecords())){
            return pageResult;
        }

        // 我们可以直接使用传递过来的userId 去查询tb_user_info
        // 拿到用户信息之后再封装数据

        //填充数据
        pageResult.setItems(this.fillQuanZiVo(pageInfo.getRecords()));

        return pageResult;
    }
    public List<VisitorsVo> queryVisitorsList() {
        User user = UserThreadLocal.get();
        List<Visitors> visitorsList = this.visitorsApi.queryMyVisitor(user.getId());
        if (CollUtil.isEmpty(visitorsList)) {
            return Collections.emptyList();
        }

        List<Object> userIds = CollUtil.getFieldValues(visitorsList, "visitorUserId");
        // 根据访客的id去查询访客的信息  tb_user_info
        List<UserInfo> userInfoList = this.userInfoService.queryUserInfoByUserIdList(userIds);

        List<VisitorsVo> visitorsVoList = new ArrayList<>();

        // 拼凑VO数据
        for (Visitors visitor : visitorsList) {
            for (UserInfo userInfo : userInfoList) {
                if (ObjectUtil.equals(visitor.getVisitorUserId(), userInfo.getUserId())) {

                    VisitorsVo visitorsVo = new VisitorsVo();
                    visitorsVo.setAge(userInfo.getAge());
                    visitorsVo.setAvatar(userInfo.getLogo()); // 用户的头像
                    visitorsVo.setGender(userInfo.getSex().name().toLowerCase());
                    visitorsVo.setId(userInfo.getUserId());  // 用户ID
                    visitorsVo.setNickname(userInfo.getNickName());
                    visitorsVo.setTags(StringUtils.split(userInfo.getTags(), ','));
                    visitorsVo.setFateValue(visitor.getScore().intValue());

                    visitorsVoList.add(visitorsVo);
                    break;
                }
            }
        }

        return visitorsVoList;
    }
}
